package com.giannini.java;

import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.newsclub.net.unix.AFUNIXServerSocket;
import org.newsclub.net.unix.AFUNIXSocketAddress;

public class UnixSocketNettyServer {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		ServerBootstrap bootstrap = new ServerBootstrap(
				new NioServerSocketChannelFactory(
						Executors.newCachedThreadPool(),
						Executors.newCachedThreadPool()));

		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			@Override
			public ChannelPipeline getPipeline() throws Exception {
				return Channels.pipeline(new MyHandler());
			}
		});

		bootstrap.bind(bindAddressString());// arg: SocketAddress

	}

	private static final String socketPath = "/home/hmail/jny/netty_socket";

	private static InetSocketAddress bindAddressString() throws IOException {
		File socketFile = new File(socketPath);

		if (!socketFile.isAbsolute()) {
			socketFile = new File("/home/hmail/jny", socketPath);
		}

		if (!socketFile.exists()) {
			// parent dir not exists, create auotmatically
			File parent = socketFile.getParentFile();
			if (!parent.exists()) {
				if (!parent.mkdirs() && !parent.exists()) {
					throw new IOException("make directory failed:" + parent);
				}
				parent.setReadable(true);
				parent.setExecutable(true);
			}
		} else if (socketFile.isDirectory()) {
			throw new IOException("illegal unix socket file:"
					+ socketFile.getAbsolutePath());
		} else {
			socketFile.delete(); // delete it
		}

		AFUNIXSocketAddress unixSocketAddress = new AFUNIXSocketAddress(
				socketFile);

		 AFUNIXServerSocket server = AFUNIXServerSocket.newInstance();
		 server.bind(unixSocketAddress);

		return (InetSocketAddress) unixSocketAddress;
	}

	private static class MyHandler extends SimpleChannelHandler {
		@Override
		public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
				throws Exception {
			// TODO Auto-generated method stub
			ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
			System.out.println(buffer.toString(Charset.defaultCharset()));
		}
	}
}
